﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Core.Common.CommandTrees;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxUploadControl;
using DevExpress.Xpo.DB;
using DevExpress.XtraSpreadsheet.Model;
using TheHeGeoCommercial.Dao;

namespace TheHeGeoCommercial.Admin
{
    public partial class UcAddProduct : System.Web.UI.UserControl
    {
        private static List<UploadedFile> upList = new List<UploadedFile>();
        private static UploadedFile avatar = null;
        private const string mainPath = @"~\ProductImage\";
        public const string UploadDirectory = "~/ProductImage/";
        private static bool isInsert = true;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["CURRENT_USER"]==null)
                Response.Redirect("~/Admin/Login.aspx");
            string callRequest = Request["id"];
            if (!IsPostBack)
            {LoadGrvData();
                LoadTypeCbb();
                if (string.IsNullOrEmpty(callRequest))
                {
                    ASPxHeadline1.HeaderText = "Thêm thông tin sản phẩm";
                    headerDetail.Visible = false;
                    grvDetail.Visible = false;
                    isInsert = true;
                    lineSpecification.Visible = true;
                    lbDetailName.Visible = true;
                    txtDetailName.Visible = true;
                    lbDetailText.Visible = true;
                    txtDetailText.Visible = true;
                    lbDetailNote.Visible = true;
                    txtDetailNote.Visible = true;
                    ASPxLabel3.Visible = true;
                    txtProductVideo.Visible = true;
                    ASPxLabel4.Visible = true;
                    txtVideoName.Visible = true;
                    lineVideo.Visible = false;
                    grvVideo.Visible = false;
                }
                else
                {
                    LoadUpdateForm(callRequest);
                    isInsert = false;
                    lineSpecification.Visible = false;
                    lbDetailName.Visible = false;
                    txtDetailName.Visible = false;
                    lbDetailText.Visible = false;
                    txtDetailText.Visible = false;
                    lbDetailNote.Visible = false;
                    txtDetailNote.Visible = false;
                    ASPxLabel3.Visible = false;
                    txtProductVideo.Visible = false;
                    ASPxLabel4.Visible = false;
                    txtVideoName.Visible = false;
                    headerDetail.Visible = true;
                    grvDetail.Visible = true;
                    lineVideo.Visible = true;
                    grvVideo.Visible = true;
                }
            }
            else
            {
                grvData.DataSource = Session["admin_ucproduct_data"];
                LoadTypeCbb();
            }
            
        }

        protected void LoadDetailForm(string maSanPham)
        {
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                var detail = (from d in ent.ChiTietSanPhams
                    join p in ent.SanPhams on d.MaSanPham equals p.MaSanPham
                    where d.MaSanPham == maSanPham
                    select new
                           {
                               d.Id,
                               p.MaSanPham,
                               p.TenSanPham,
                               d.SpecificationName,
                               d.SpecificationTxt,
                               d.SpecificationNote
                           }).ToList();
                DataTable dt = new DataTable();
                dt.Columns.Add("Id", typeof(int));
                dt.Columns.Add("MaSanPham", typeof(string));
                dt.Columns.Add("TenSanPham", typeof(string));
                dt.Columns.Add("SpecificationName", typeof(string));
                dt.Columns.Add("SpecificationTxt", typeof(string));
                dt.Columns.Add("SpecificationNote", typeof(string));
                if (detail.Count > 0)
                {
                   
                    foreach (var dtObj in detail)
                    {
                        var dr = dt.NewRow();
                        dr["Id"] = dtObj.Id;
                        dr["MaSanPham"] = dtObj.MaSanPham;
                        dr["TenSanPham"] = dtObj.TenSanPham;
                        dr["SpecificationName"] = dtObj.SpecificationName;
                        dr["SpecificationTxt"] = dtObj.SpecificationTxt;
                        dr["SpecificationNote"] = dtObj.SpecificationNote;
                        dt.Rows.Add(dr);
                    }
                }
                grvDetail.DataSource = dt;
                grvDetail.DataBind();
            }
        }
        protected void LoadUpdateForm(string maSanPham)
        {
            ASPxHeadline1.HeaderText = "Sửa thông tin sản phẩm";
            txtMaSanPham.ReadOnly = true;
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                var obj = (from s in ent.SanPhams
                    join l in ent.LoaiSanPhams on s.MaLoaiSanPham equals l.MaLoaiSanPham
                           where s.MaSanPham == maSanPham
                    select new
                           {
                               s.MaSanPham,
                               s.TenSanPham,
                               s.ChuThich,
                               l.TenLoaiSanPham,
                               s.MaLoaiSanPham,
                               s.ImageUrl,
                               s.ImageDirectory,

                               s.Gia
                           }).FirstOrDefault();
                if (obj != null)
                {
                    txtMaSanPham.Text = obj.MaSanPham;
                    txtTenSanPham.Text = obj.TenSanPham;
                    txtChuThich.Text = obj.ChuThich;
                    cbbLoaiSanPham.Value = obj.MaLoaiSanPham;
                    txtGia.Text = obj.Gia;
                } 
            }
            LoadDetailForm(maSanPham);
            LoadGrvVideo(maSanPham);
            LoadPhoto(maSanPham);}
        protected void LoadTypeCbb()
        {
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                var typeProduct = (from t in ent.LoaiSanPhams
                    select t).ToList();
                cbbLoaiSanPham.DataSource = typeProduct;
                cbbLoaiSanPham.TextField = "TenLoaiSanPham";
                cbbLoaiSanPham.ValueField = "MaLoaiSanPham";
                cbbLoaiSanPham.DataBind();}
           

        }
        private void LoadGrvData()
        {
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                var obj = (from s in ent.SanPhams
                    join l in ent.LoaiSanPhams on s.MaLoaiSanPham equals l.MaLoaiSanPham
                    //join d in ent.ChiTietSanPhams on s.MaSanPham equals  d.MaSanPham
                    select new
                           {
                               s.MaSanPham,
                               s.TenSanPham,
                               s.ChuThich,
                               l.TenLoaiSanPham,
                               s.MaLoaiSanPham,
                               s.ImageUrl,
                               s.ImageDirectory,
                               //d.SpecificationName,
                               //d.SpecificationNote,
                               //d.SpecificationTxt,
                               s.Gia
                           }).ToList();
                Session["admin_ucproduct_data"] = obj;
                grvData.DataSource = obj;
                grvData.DataBind();
            }
            
        }

        private void LoadPhoto(string maSanPham)
        {
            var dt = new DataTable();
            dt.Columns.Add("MaSanPham");
            dt.Columns.Add("TenSanPham");
            dt.Columns.Add("ImageUrl");
            dt.Columns.Add("TenAnh");
           
            string folder = UploadDirectory + maSanPham;
            string newPath = Server.MapPath(folder);
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            string[] files = Directory.GetFiles(newPath);
            if (files.Length > 0)
            {
                foreach (var file in files)
                {
                    var dr = dt.NewRow();
                    dr["MaSanPham"] = maSanPham;
                    dr["TenSanPham"] = txtTenSanPham.Text;
                    dr["TenAnh"] = Path.GetFileName(file);
                    dr["ImageUrl"] = mainPath + @"\" + maSanPham + @"\" + Path.GetFileName(file); ;
                    dt.Rows.Add(dr);
                }
                
            }
            ASPxDataView2.DataSource = dt;
            ASPxDataView2.DataBind();
        }
        private void LoadGrvVideo(string maSanPham)
        {
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                var detail = (from d in ent.ProductVideos
                              join p in ent.SanPhams on d.MaSanPham equals p.MaSanPham
                              where d.MaSanPham == maSanPham
                              select new
                              {
                                  d.Id,
                                  p.MaSanPham,
                                  p.TenSanPham,
                                  d.VideoLink,
                                  d.VideoName
                                
                              }).ToList();
                DataTable dt = new DataTable();
                dt.Columns.Add("Id", typeof(int));
                dt.Columns.Add("MaSanPham", typeof(string));
                dt.Columns.Add("TenSanPham", typeof(string));
                dt.Columns.Add("VideoLink", typeof(string));
                dt.Columns.Add("VideoName", typeof(string));

                if (detail.Count > 0)
                {

                    foreach (var dtObj in detail)
                    {
                        var dr = dt.NewRow();
                        dr["Id"] = dtObj.Id;
                        dr["MaSanPham"] = dtObj.MaSanPham;
                        dr["TenSanPham"] = dtObj.TenSanPham;
                        dr["VideoLink"] = dtObj.VideoLink;
                        dr["VideoLink"] = dtObj.VideoName;

                        dt.Rows.Add(dr);
                    }
                }
                grvVideo.DataSource = dt;
                grvVideo.DataBind();
            }
        }
        protected bool ValidateProduct()
        {
            var maSp = txtMaSanPham.Text.Trim(' ');
            if (string.IsNullOrEmpty(maSp))
            {
                Response.Write("<script LANGUAGE='JavaScript' >alert('Bạn chưa nhập mã sản phẩm.');document.location='" + ResolveClientUrl("/Admin/AddProduct.aspx") + "';</script>");
                return false;
            }
            else
            {
                using (var ent = new Dao.TheheGeoCommercialEntities())
                {
                    var obj = (from i in ent.SanPhams
                        where i.MaLoaiSanPham == maSp
                        select i).FirstOrDefault();
                    if (obj != null)
                    {
                        Response.Write(
                            "<script LANGUAGE='JavaScript' >alert('Mã sản phẩm đã tồn tại trong hệ thống.');document.location='" +
                            ResolveClientUrl("/Admin/AddProduct.aspx") + "';</script>");
                        return false;
                    }
                   
                }
            }
            if (string.IsNullOrEmpty(txtTenSanPham.Text.Trim(' ')))
            {
                Response.Write("<script LANGUAGE='JavaScript' >alert('Bạn chưa nhập tên sản phẩm.');document.location='" + ResolveClientUrl("/Admin/AddProduct.aspx") + "';</script>");
                return false;
            }
            if (cbbLoaiSanPham.Value == null)
            {
                Response.Write(
                    "<script LANGUAGE='JavaScript' >alert('Bạn chưa chọn loại sản phẩm.');document.location='" +
                    ResolveClientUrl("/Admin/AddProduct.aspx") + "';</script>");
                return false;
            }
            if (string.IsNullOrEmpty(txtGia.Text.Trim(' ')))
            {
                Response.Write("<script LANGUAGE='JavaScript' >alert('Bạn chưa nhập giá của sản phẩm.');document.location='" + ResolveClientUrl("/Admin/AddProduct.aspx") + "';</script>");
                return false;
            }
            return true;
        }

        protected void InsertProduct(){

            if (ValidateProduct())
            {
                try
                {
                    var product = new SanPham();
                    
                    product.MaSanPham = txtMaSanPham.Text;
                    product.TenSanPham = txtTenSanPham.Text;
                    product.MaLoaiSanPham = cbbLoaiSanPham.Value.ToString();
                    product.Gia = txtGia.Text ;
                    product.ChuThich = txtChuThich.Text; if (avatar != null)
                        product.ImageUrl = mainPath + txtMaSanPham.Text + @"\" + avatar.FileName;
                    product.ImageDirectory = mainPath + txtMaSanPham.Text + @"\";
                    var detail = new ChiTietSanPham();
                    detail.MaSanPham = txtMaSanPham.Text;detail.SpecificationName = txtDetailName.Text;
                    detail.SpecificationTxt = txtDetailText.Text;
                    detail.SpecificationNote = txtDetailNote.Text;
                    var productVideo = new ProductVideo();
                    productVideo.MaSanPham = txtMaSanPham.Text;
                    productVideo.VideoLink = txtProductVideo.Text;
                    productVideo.VideoName = txtVideoName.Text;
                   
                    using (var ent = new Dao.TheheGeoCommercialEntities())
                    {
                        ent.SanPhams.Add(product);
                        if (!string.IsNullOrEmpty(txtDetailName.Text))
                            ent.ChiTietSanPhams.Add(detail);
                        if (!string.IsNullOrEmpty(txtProductVideo.Text))
                            ent.ProductVideos.Add(productVideo);
                        ent.SaveChanges();
                    }
        
                    Response.Write(
                   "<script LANGUAGE='JavaScript' >alert('Insert sản phẩm thành công.');document.location='" +
                   ResolveClientUrl("/Admin/AddProduct.aspx") + "';</script>");
                }
                catch (Exception)
                {

                    Response.Write(
                   "<script LANGUAGE='JavaScript' >alert('Insert sản phẩm không thành công.');document.location='" +
                   ResolveClientUrl("/Admin/AddProduct.aspx") + "';</script>");
                }
                
            }
        }
        protected void UpdateProduct()
        {
            try
            {
                using (var ent = new Dao.TheheGeoCommercialEntities())
                {
                    var p = (from i in ent.SanPhams where i.MaSanPham == txtMaSanPham.Text select i).FirstOrDefault();
                    if (p != null)
                    {
                        p.TenSanPham = txtTenSanPham.Text;
                        p.MaLoaiSanPham = cbbLoaiSanPham.Value.ToString();
                        p.Gia = txtGia.Text;
                        p.ChuThich = txtChuThich.Value.ToString();
                        if (avatar != null)
                            p.ImageUrl = mainPath + txtMaSanPham.Text + @"\" + avatar.FileName;
                    }
                    ent.SaveChanges();
                    //isInsert = true;
                    //txtMaSanPham.ReadOnly = false;
                }
                Response.Write(
                    "<script LANGUAGE='JavaScript' >alert('Update sản phẩm thành công.');document.location='" +
                    ResolveClientUrl("/Admin/AddProduct.aspx") + "';</script>");
            }
            catch (Exception ex)
            {
                Response.Write(
                    "<script LANGUAGE='JavaScript' >alert('Update sản phẩm không thành công.');document.location='" +
                    ResolveClientUrl("/Admin/AddProduct.aspx") + "';</script>");
            }
           
        }
        protected void UploadFile()
        {
            SavePostedFiles(avatar);
            avatar = null;
            if(upList.Count>0)
                foreach (var uploadFile in upList)
                {
                    SavePostedFiles(uploadFile);
                }
            upList.Clear();
        }
        void SavePostedFiles(UploadedFile uploadedFile)
        {
            if(uploadedFile==null)
                return;
            if (!uploadedFile.IsValid)return ;
            if (uploadedFile.ContentLength <= 0)
                return;
    
            string fileName = uploadedFile.FileName;
            var fileInfo = new FileInfo(uploadedFile.FileName);
            var newPath = Server.MapPath(UploadDirectory + txtMaSanPham.Text.Trim() + "/");
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            string resFileName = newPath + fileName;

            try
            {
                uploadedFile.SaveAs(resFileName);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Request["id"]))
                InsertProduct();
            else
            {
                UpdateProduct();
            }
            UploadFile();
            LoadGrvData();
        }

        protected void uploadAvatar_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
        {
            try
            {
                avatar = e.UploadedFile;
            }
            catch (Exception ex)
            {
                e.IsValid = false;
                e.ErrorText = ex.Message;
            }
        }

        protected void uploadImages_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
        {
            try
            {
                if (avatar != null && e.UploadedFile.FileName != avatar.FileName)
                    return;
                 upList.Add(e.UploadedFile);
            }catch (Exception ex)
            {
                e.IsValid = false;
                e.ErrorText = ex.Message;
            }
        }

        protected void LoadGrvProducType()
        {
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                var obj = (from i in ent.LoaiSanPhams
                           select i).ToList();
                var dt = new DataTable();
                dt.Columns.Add("MaLoaiSanPham", typeof(string));
                dt.Columns.Add("TenLoaiSanPham", typeof(string));
                dt.Columns.Add("ChuThich", typeof(string));
                if (obj.Count > 0)
                    foreach (var loaiSanPham in obj)
                    {
                        var dr = dt.NewRow();
                        dr["MaLoaiSanPham"] = loaiSanPham.MaLoaiSanPham;
                        dr["TenLoaiSanPham"] = loaiSanPham.TenLoaiSanPham;
                        dr["ChuThich"] = loaiSanPham.ChuThich;
                        dt.Rows.Add(dr);
                    }
                grvProductType.DataSource = dt;
                grvProductType.DataBind();
            }
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
           popupAddType.ShowOnPageLoad = true;
           LoadGrvProducType();
        }

        //protected void btnSaveType_Click(object sender, EventArgs e)
        //{
        //    var type = txtProductType.Text.Trim();
        //    var typeId = txtProductType.Text.Trim();
        //    if (string.IsNullOrEmpty(type) || string.IsNullOrEmpty(typeId))
        //    {
        //        Response.Write("<script LANGUAGE='JavaScript' >alert('Chưa nhập đủ thông tin');document.location='" + ResolveClientUrl("/Admin/AddProduct.aspx") + "';</script>");
        //        return;  
        //    }
        //    else
        //    {
        //        using (var ent = new Dao.TheheGeoCommercialEntities())
        //        {
        //            var obj = (from i in ent.LoaiSanPhams
        //                       where i.TenLoaiSanPham == typeId
        //                       select i).FirstOrDefault();
        //            if (obj != null)
        //            {
        //                Response.Write(
        //                    "<script LANGUAGE='JavaScript' >alert('Loại sản phẩm đã tồn tại trong hệ thống.');document.location='" +
        //                    ResolveClientUrl("/Admin/AddProduct.aspx") + "';</script>");
        //                return ;
        //            }
        //            var productType = new LoaiSanPham();
        //            productType.MaLoaiSanPham = typeId;productType.TenLoaiSanPham = type;
        //            productType.ChuThich = txtTypeNote.Text;
        //            ent.LoaiSanPhams.Add(productType);
        //            ent.SaveChanges();
        //        }
        //     }
        //    popupAddType.ShowOnPageLoad = false;
        //}

        void DeleteProduct(int rowIndex)
        {
            try
            {
                var productId = grvData.GetRowValues(rowIndex, "MaSanPham");
                
                using (var ent = new Dao.TheheGeoCommercialEntities())
                {

                    var detail = (from d in ent.ChiTietSanPhams
                                  where d.MaSanPham == productId
                                  select d).ToList();
                    if (detail.Count > 0)
                        ent.ChiTietSanPhams.RemoveRange(detail);

                    var product = (from p in ent.SanPhams where p.MaSanPham == productId select p).FirstOrDefault();
                    if (product != null)
                        ent.SanPhams.Remove(product);
                    ent.SaveChanges();
                }
                //Response.Write(
                //    "<script LANGUAGE='JavaScript' >alert('Xóa sản phẩm thành công.');document.location='" +
                //    ResolveClientUrl("/Admin/AddProduct.aspx") + "';</script>");
                LoadGrvData();}
            catch (Exception)
            {

                //Response.Write(
                //    "<script LANGUAGE='JavaScript' >alert('Xóa sản phẩm không thành công.');document.location='" +
                //    ResolveClientUrl("/Admin/AddProduct.aspx") + "';</script>");
            }
            
        }
        void EditProduct(int rowIndex)
        {
            
            ASPxHeadline1.HeaderText = "Sửa Thông tin sản phẩm";
            var productId = grvData.GetRowValues(rowIndex, "MaSanPham");

            DevExpress.Web.ASPxClasses.ASPxWebControl.RedirectOnCallback("~/Admin/AddProduct.aspx?id=" + productId);

        }

        void AddProduct(int rowIndex)
        {
            DevExpress.Web.ASPxClasses.ASPxWebControl.RedirectOnCallback("~/Admin/AddProduct.aspx");
        }
        protected void grvData_CustomButtonCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            switch (e.ButtonID)
            {
                case "btnDelete":
                    DeleteProduct(e.VisibleIndex);
                    break;

                case "btnEdit":
                    isInsert = false;
                    EditProduct(e.VisibleIndex);
                    break;
                case "btnNew":
                    isInsert = true;
                    AddProduct(e.VisibleIndex);
                    break;

            }
        }

        protected void grvDetail_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            var id =  Convert.ToInt32(e.Values["Id"].ToString());
            var maSanPham = e.Values["MaSanPham"].ToString();
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                var detail = (from d in ent.ChiTietSanPhams where d.Id == id select d).FirstOrDefault();
                if (detail != null)
                {
                    ent.ChiTietSanPhams.Remove(detail);
                    ent.SaveChanges();
                }
            }
            e.Cancel = true;
            grvDetail.CancelEdit();
            LoadDetailForm(maSanPham);
        }

        protected void grvDetail_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            var maSanPham = e.NewValues["MaSanPham"].ToString();
            var tenDetail = e.NewValues["SpecificationName"].ToString();
            var nDungDetail = e.NewValues["SpecificationTxt"].ToString();
            var noteDetail = "";
            noteDetail = e.NewValues["noteDetail"]!=null ? e.NewValues["SpecificationNote"].ToString() : string.Empty;
            var productDetail = new ChiTietSanPham();
            productDetail.MaSanPham = maSanPham;
            productDetail.SpecificationName = tenDetail;
            productDetail.SpecificationTxt = nDungDetail;
            productDetail.SpecificationNote = noteDetail;
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                ent.ChiTietSanPhams.Add(productDetail);
                ent.SaveChanges();
            }
            e.Cancel = true;
            grvDetail.CancelEdit();
            LoadDetailForm(maSanPham);
        }

        protected void grvDetail_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            var id = Convert.ToInt32(grvDetail.GetRowValues(grvDetail.EditingRowVisibleIndex,"Id"));
            var maSanPham = e.NewValues["MaSanPham"].ToString();
            var tenDetail = e.NewValues["SpecificationName"].ToString();
            var nDungDetail = e.NewValues["SpecificationTxt"].ToString();
            var noteDetail = "";
            noteDetail = e.NewValues["noteDetail"] != null ? e.NewValues["SpecificationNote"].ToString() : string.Empty;
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                var detail = (from d in ent.ChiTietSanPhams where d.Id == id select d).FirstOrDefault();
                if (detail != null)
                {
                    detail.SpecificationName = tenDetail;
                    detail.SpecificationTxt = nDungDetail;
                    detail.SpecificationNote = noteDetail;
                    ent.SaveChanges();
                }
            }
            e.Cancel = true;
            grvDetail.CancelEdit();
            LoadDetailForm(maSanPham);
        }

        protected void grvDetail_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
        {
            e.NewValues["MaSanPham"] = txtMaSanPham.Text;
            e.NewValues["TenSanPham"] = txtTenSanPham.Text;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            DevExpress.Web.ASPxClasses.ASPxWebControl.RedirectOnCallback("~/Admin/AddProduct.aspx");}

        protected void grvVideo_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
        {
            e.NewValues["MaSanPham"] = txtMaSanPham.Text;
            e.NewValues["TenSanPham"] = txtTenSanPham.Text;
        }

        protected void grvVideo_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            var id = Convert.ToInt32(e.Values["Id"].ToString());
            var maSanPham = e.Values["MaSanPham"].ToString();
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                var detail = (from d in ent.ProductVideos where d.Id == id select d).FirstOrDefault();
                if (detail != null)
                {
                    ent.ProductVideos.Remove(detail);
                    ent.SaveChanges();
                }
            }
            e.Cancel = true;
            grvVideo.CancelEdit();
            LoadGrvVideo(maSanPham);
        }

        protected void grvVideo_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            var maSanPham = e.NewValues["MaSanPham"].ToString();
            var productLink = e.NewValues["VideoLink"].ToString();
            var videoName = e.NewValues["VideoName"].ToString();var productVideo = new ProductVideo();
            productVideo.MaSanPham = maSanPham;
            productVideo.VideoLink = @productLink;
            productVideo.VideoName = videoName;
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                
                    ent.ProductVideos.Add(productVideo);
                    ent.SaveChanges();
            }
            e.Cancel = true;
            grvVideo.CancelEdit();
            LoadGrvVideo(maSanPham);
        }

        protected void grvVideo_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            var maSanPham = e.NewValues["MaSanPham"].ToString();
            var id = Convert.ToInt32(grvVideo.GetRowValues(grvVideo.EditingRowVisibleIndex, "Id"));
            var productLink = e.NewValues["VideoLink"].ToString();
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                var productVideo = (from d in ent.ProductVideos where d.Id == id select d).FirstOrDefault();
                if (productVideo != null)
                {
                    productVideo.VideoLink = productLink;
                    ent.SaveChanges();
                }
            }
            e.Cancel = true;
            grvVideo.CancelEdit();
            LoadGrvVideo(maSanPham);
        }

        protected void ASPxDataView2_CustomCallback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            try
            {
                string folder = UploadDirectory + txtMaSanPham.Text+"/";string newPath = Server.MapPath(folder) + e.Parameter;
                File.Delete(newPath);
                LoadPhoto(txtMaSanPham.Text);}
            catch (Exception)
            {
                
                throw;
            }
        }

        protected void grvProductType_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            var id = e.Values["MaLoaiSanPham"].ToString();
            
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                var detail = (from d in ent.LoaiSanPhams where d.MaLoaiSanPham == id select d).FirstOrDefault();
                if (detail != null)
                {
                    ent.LoaiSanPhams.Remove(detail);
                    ent.SaveChanges();
                }
            }
            e.Cancel = true;
            grvProductType.CancelEdit();
            LoadGrvProducType();
        }

        protected void grvProductType_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            var maLoaiSanPham = e.NewValues["MaLoaiSanPham"].ToString();
            var tenLoaiSanPham = e.NewValues["TenLoaiSanPham"].ToString();
            var chuThich = e.NewValues["ChuThich"].ToString(); 
            var productType = new LoaiSanPham();
            productType.MaLoaiSanPham = maLoaiSanPham;
            productType.TenLoaiSanPham = tenLoaiSanPham;
            productType.ChuThich = chuThich;
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {

                ent.LoaiSanPhams.Add(productType);
                ent.SaveChanges();}
            e.Cancel = true;
            grvProductType.CancelEdit();
            LoadGrvProducType();
        }

        protected void grvProductType_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            var maLoaiSanPham = e.OldValues["MaLoaiSanPham"].ToString();
            var tenLoaiSanPham = e.NewValues["TenLoaiSanPham"].ToString();
            var chuThich = e.NewValues["ChuThich"].ToString(); 
            using (var ent = new Dao.TheheGeoCommercialEntities())
            {
                var productType = (from d in ent.LoaiSanPhams where d.MaLoaiSanPham == maLoaiSanPham select d).FirstOrDefault();
                if (productType != null)
                {
                    productType.TenLoaiSanPham = tenLoaiSanPham;
                    productType.ChuThich = chuThich;
                    ent.SaveChanges();
                }
            }
            e.Cancel = true;
            grvProductType.CancelEdit();
            LoadGrvProducType();}

        protected void grvProductType_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
        {
            var c = grvProductType.Columns["MaLoaiSanPham"] as GridViewDataColumn;
            if (c != null)
            {
                c.ReadOnly = false;
            }
        }
    }
}